package db_main

import (
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"
)

func GetOfflineMsg(param map[string]interface{}) ([]*models_main.OfflineMsg, error) {
	fName := "GetOfflineMsg"
	o := make([]*models_main.OfflineMsg, 0)
	table := mysql.GetRTable(&models_main.OfflineMsg{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Scan(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

// 取得後台設定的發送請求
func GetBackofficeToSend() ([]*models_main.OfflineMsg, error) {
	fName := "GetOfflineMsgByTime"
	o := make([]*models_main.OfflineMsg, 0)
	table := mysql.GetRTable(&models_main.OfflineMsg{})
	err := table.Where("push_time <= ? AND push_status = ? OR push_status = ?", time.Now().Unix(), 1, 3).Scan(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertOfflineMsg(o *models_main.OfflineMsg) error {
	fName := "InsertOfflineMsg"
	err := global.GetR().Model(&models_main.OfflineMsg{}).Create(o).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateOfflineMsg(offlineMsg []*models_main.OfflineMsg) error {
	fName := "UpdateOfflineMsg"
	err := global.GetR().Model(&models_main.OfflineMsg{}).Save(offlineMsg).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
